<template>
  <div class="diy_edit user_edits" id="user_edit">
    <el-form
        :model="form"
        ref="ruleFormRef"
        :rules="rules"
        label-width="auto"
        class="edit_user_form"
        size="large"
    >
      <el-row class="row_e">
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="头像" prop="avatar">
            <el-upload
                class="avatar-uploader"
                drag
                accept="image/jpeg, image/png, image/jpg"
                action=""
                :http-request="uploadimg"
                :show-file-list="false"
            >
              <img
                  v-if="form.avatar"
                  :src="$fullUrl($banseUrl, form.avatar)"
                  class="avatar"
              />
              <el-icon v-else>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="用户名" prop="username">
            <span v-if="obj.username">{{ obj.username }}</span>
            <el-input
                v-else
                v-model="form.username"
                placeholder="请输入用户名"
                autocomplete="new-password"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="昵称" prop="nickname">
            <el-input
                v-model="form.nickname"
                placeholder="请输入昵称"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="密码" prop="password">
            <span v-if="obj.password">{{ obj.password }}</span>
            <el-input
                v-else
                type="password"
                v-model="form.password"
                placeholder="请输入密码"
                show-password
                autocomplete="new-password"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="邮箱" prop="email">
            <el-input
                type="email"
                v-model="form.email"
                placeholder="请输入邮箱"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <span></span>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="状态" prop="state">
            <el-select v-model="form.state" placeholder="请选择">
              <el-option
                  v-for="group in list_user_state"
                  :key="group.value"
                  :label="group.name"
                  :value="group.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="footer">
        <el-button type="primary" @click="Onsubmit" size="large"
        >提交
        </el-button
        >
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import {ElMessage} from "element-plus";
import {ref, onMounted} from "vue";
import {$post, $get} from "@/api/Api.js";
import storageHelper from "@/libs/StorageHelper";
import {useStore} from "vuex";
import {useRouter} from "vue-router";
import {
  $get_auth,
  func,
  paramsFun,
  $fullUrl,
  formatDate,
  $banseUrl,
  $check_action,
  $getUrlParams,
  filterSensitiveWords,
} from "@/utils/utils.js";

let router = useRouter();
let store = useStore();
let token = storageHelper.getToken() || null;
let UserInfo = storageHelper.getUserInfo();
let user_id = $getUrlParams().user_id;
let url_add = ref("/api/user/add");
let url_set = ref("/api/user/set");
let url_upload = ref("/api/user/upload");
let url_get_obj = ref("/api/user/get_obj");
let title = ref("user");
let field = ref("user_id");
// 用户组
let list_user_group = ref([]);
// 账号状态
let list_state = ref([
  {
    text: "可用",
    value: 1,
  },
  {
    text: "异常",
    value: 2,
  },
  {
    text: "已冻结",
    value: 3,
  },
  {
    text: "已注销",
    value: 4,
  },
]);
// 认证状态
let list_user_state = ref([
  {
    value: 1,
    name: "可用",
  },
  {
    value: 2,
    name: "异常",
  },
  {
    value: 3,
    name: "已冻结",
  },
  {
    value: 4,
    name: "已注销",
  },
]);

let form = ref({
  user_id: 0,
  username: "",
  nickname: "",
  password: "",
  avatar: "",
  email: "",
  state: 1,
  vip_level: "",
  user_group: "管理员",
  vip_discount: 0,
});

let obj = ref({
  user_id: 0,
  username: "",
  nickname: "",
  password: "",
  avatar: "",
  // phone: '',
  email: "",
  user_group: "管理员",
  // phone_state: 0,
  // email_state: 0,
  state: 1,
  vip_level: "",
  vip_discount: 0,
});
let ruleFormRef = ref(null);
let rules = ref({
  nickname: [
    {
      required: true,
      message: "请输入昵称",
      trigger: "blur",
    },
    {
      min: 2,
      max: 12,
      message: "昵称长度应为2个字符到12个字符之间",
      trigger: "blur",
    },
  ],
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
    {
      min: 5,
      max: 25,
      message: "长度在 5 到 25 个字符",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
  email: [
    {
      type: "email",
      message: "必须是邮箱格式，例：test@test.com",
      trigger: "blur",
    },
  ],
});
// 点击取消
let cancel = () => {
  router.go(-1);
};
// 点击提交
let Onsubmit = async () => {
  let valid = await ruleFormRef.value.validate();
  if (valid) {
    if (user_id) {
      // 编辑
      $post(url_set.value + "?user_id=" + user_id, form.value).then((res) => {
        if (res.result) {
		  storageHelper.setUserInfo(form.value)
          ruleFormRef.value.resetFields();
          router.push("/home/user/table");
          ElMessage.success("提交成功！");
        } else if (res.error) {
          ElMessage.error(res.error.message);
        }
      });
    } else {
      // 新增
      $post(url_add.value, form.value).then((res) => {
        if (res.result) {
		  storageHelper.setUserInfo(form.value)
          ruleFormRef.value.resetFields();
          router.push("/home/user/table");
          ElMessage.success("提交成功！");
        } else if (res.error) {
          ElMessage.error(res.error.message);
        }
      });
    }
  } else {
    ElMessage.error(msg);
  }
};
// 获取详情
let get_user_obj = async () => {
  let list = await $get("/api/user/get_obj?user_id=" + user_id);
  form.value = list.result.obj;
  obj.value = list.result.obj;
};
/**
 * 判断图片类型和大小
 * @param {Object} file
 * @return {Boolen} 符合条件时返回true, 不符合条件时返回false
 */
let beforeAvatarUpload = (file) => {
  console.log("判断");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (file.type !== "image/jpg") {
    ElMessage.error("上传头像图片只能是 JPG 格式!");
  } else if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isLt2M;
};
// 上传头像
let uploadimg = (param) => {
  uploadFile(param.file, "avatar");
};
/**
 * 上传头像
 * @param {Object} file 文件对象
 * @param {key} 保存键名
 */
const uploadFile = (file, key = "img") => {
  var formobj = new FormData(); // FormData 对象
  formobj.append("file", file); // 文件对象
  $upload(url_upload.value, formobj, function (json) {
    if (json.result) {
      form.value[key] = json.result.url;
    } else {
      ElMessage.error("上传失败！");
    }
  });
};
/**
 * 上传文件
 * @param {String} url 请求地址
 * @param {Object} body 请求参数
 * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
 * @return {Object} 返回请求结果
 */
let $upload = async (url, body, func) => {
  url = url.replace("~/", $banseUrl);
  if (func) {
    // 如果回调函数存在, 则采用异步
    $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    })
        .then((res) => {
          func(res);
        })
        .catch((res) => {
          func(res);
        });
  } else {
    // 否则采用同步
    var res = await $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    });
    return res;
  }
};
//获取用户
let get_list_user_group = async () => {
  let json = await $get("/api/user/get_list");
  if (json.result) {
    list_user_group.value = json.result.list;
  } else if (json.error) {
    console.error(json.error);
  }
};
onMounted(() => {
  get_list_user_group();
  if(user_id){
	get_user_obj();
  }
});
</script>

<style scoped lang="less">
.diy_edit {
  width: 100%;

  .edit_user_form {
    max-width: 60%;
    margin: 90px auto;

    .fn {
      width: 100%;
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .edit_list_user_sell {
    width: 80%;
    margin: 90px auto;
  }

  .footer {
    text-align: center;
  }
}
</style>
